package com.itljm.cxrMarket.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itljm.cxrMarket.common.PageResult;
import com.itljm.cxrMarket.common.Result;
import com.itljm.cxrMarket.common.StatusCode;
import com.itljm.cxrMarket.entity.LoginUser;
import com.itljm.cxrMarket.entity.SysUser;
import com.itljm.cxrMarket.entity.dto.HomeCountDataDTO;
import com.itljm.cxrMarket.entity.dto.MerchantRegisterDTO;
import com.itljm.cxrMarket.entity.dto.ResetPwdDTO;
import com.itljm.cxrMarket.mapper.SysUserRoleMapper;
import com.itljm.cxrMarket.service.SysUserService;
import com.itljm.cxrMarket.utils.CaptchaUtil;
import com.itljm.cxrMarket.utils.RedisUtil;
import com.itljm.cxrMarket.utils.StringUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ljm
 * @date 2024/11/18 9:06
 */
@RestController
@RequestMapping("/sysUser")
@CrossOrigin
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;

    // 登录接口
    @PostMapping("/login")
    public Result login(@RequestBody SysUser sysUser) {
        Map<String, Object> login = sysUserService.login(sysUser);
        return Result.ok(login);
    }

    @RequestMapping("/code")
    public void getCode(HttpServletResponse response) {
        try {
            String code = CaptchaUtil.getCode(response);
            System.out.println("生成的验证码：" + code);
            redisUtil.setCacheObject("captcha", code, 60, TimeUnit.SECONDS);
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 注册接口
    @PostMapping("/register")
    public Result register(@RequestBody MerchantRegisterDTO entity) {
        boolean register = sysUserService.register(entity);
        if (register){
            return Result.ok("注册成功");
        }
        return Result.fail("注册失败");
    }

    // 修改密码
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody ResetPwdDTO resetPwdDTO) {
        SysUser user = sysUserService.selectById(resetPwdDTO.getId());
        if (passwordEncoder.matches(resetPwdDTO.getOldPassword(), user.getPassword())){
            user.setPassword(resetPwdDTO.getNewPassword());// 设置新密码
        }else {
            return Result.fail("旧密码错误");
        }
        boolean res = sysUserService.updatePassword(user);
        if (res){
            return Result.ok("修改成功");
        }
        return Result.fail("修改失败");
    }

    // 退出登录
    @GetMapping("/logout")
    public Result logout() {
        // 通过SecurityContextHolder获取当前用户的认证信息
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        if (ObjectUtils.isNull(loginUser)) {
            return Result.fail(StatusCode.UNAUTHORIZED);
        }
        String userId = loginUser.getUser().getId().toString();
        // 删除redis中当前用户信息、刷新令牌的缓存
        redisUtil.deleteObject("user:"+userId);
        redisUtil.deleteObject("RefreshToken:"+userId);
        // 清除SecurityContextHolder中的认证信息
        SecurityContextHolder.clearContext();
        return Result.ok("注销成功");
    }

    // 获取工作台统计数据
    @GetMapping("/totalDataInfo")
    public Result dashboard() {
        HomeCountDataDTO countData = sysUserService.getHomeCountData();
        if (ObjectUtils.isNull(countData)) {
            return Result.fail("数据获取失败");
        }
        return Result.ok(countData);
    }

    /**
     * 分页查询
     * @return PageResult<SysUser>
     */
    @GetMapping("/info")
//    @PreAuthorize("@securityAuthority.hasAuthority('query:user:list')")
    public PageResult<SysUser> info(Integer page, Integer limit,
                                    String username, String role,
                                    String startCreateTime,String endCreateTime) {
        if (page == null) {
            page = 0;
        }
        if (limit == null) {
            limit = 15;
        }
        Page<SysUser> userPage = new Page<>(page, limit);

        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("1",1);
        if (StringUtils.isNotEmpty(username)) {
            wrapper.like("username",username);
        }
        if (StringUtils.isNotEmpty(role)) {
            wrapper.eq("sur.role_id",role);
        }
        if (StringUtils.isNotEmpty(startCreateTime) && StringUtils.isNotEmpty(endCreateTime)) {
            wrapper.ge("create_time",startCreateTime).le("create_time",endCreateTime);
        }
        List<SysUser> userList = sysUserService.selectUserPage(userPage, wrapper);
        return new PageResult<>(userList, userPage.getTotal());
    }

    /**
     * 根据用户名查询
     */
    @GetMapping("/infoByName")
    public Result<SysUser> infoByUsername(@RequestParam String username) {
        SysUser sysUser = sysUserService.selectByUserName(username);
        return Result.ok(sysUser);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/info/{id}")
    public Result<SysUser> infoById(@PathVariable Long id) {
        SysUser sysUser = sysUserService.selectById(id);
        return Result.ok(sysUser);
    }

    /**
     * 获取个人信息
     */
    @GetMapping("/profile/{id}")
    public Result<SysUser> profile(@PathVariable Long id) {
        SysUser sysUser = sysUserService.selectById(id);
        return Result.ok(sysUser);
    }

    /**
     * 新增或修改
     */
    @PostMapping("/save")
    public Result save(@RequestBody SysUser sysUser) {
        if (sysUser.getId() != null) {
            sysUser.setUpdateTime(new Date());
            return Result.ok(sysUserService.updateById(sysUser));
        }else {
            sysUser.setPassword(passwordEncoder.encode("123456"));
            sysUser.setCreateTime(new Date());
            return Result.ok(sysUserService.insert(sysUser));
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        return Result.ok(sysUserService.deleteById(id));
    }


}
